<template>
  <div class="search">
    <div class="search-input">
      <input type="text" placeholder="请输入城市名查询" v-model="keyword">
    </div>
    <div class="search-content" ref="wrapper" v-show="keyword">
      <ul>
        <li class="border-bottom" v-for="item of list" :key="item.id" @click="handleCityClick(item.name)">{{item.name}}</li>
        <li v-show="hasNoData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import Bscroll from 'better-scroll'
export default {
  name: 'citySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
        // console.log(result)
      }, 100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.wrapper)
  },
  methods: {
    handleCityClick (city) {
      // this.$store.dispatch('changeCity', city)
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapActions(['changeCity'])
  }
}
</script>
<style lang="stylus" scoped>
@import "~css/variable.styl"
  .search
    &-input
      height .72rem
      padding 0 .1rem
      background $headerBGC
      input
        box-sizing border-box
        width 100%
        height .62rem
        padding 0 .1rem
        line-height .62rem
        text-align center
        border-radius .06rem
        color #666
    &-content
      overflow hidden
      position absolute
      z-index 1
      top 1.58rem
      // left 0
      // right 0
      bottom 0
      width 6.4rem
      margin 0 auto
      padding 0 .2rem
      background #fff
      ul
        li
          height .5rem
          line-height .5rem

</style>
